package com.zjitc.backend_shop.service.Impl;
import com.alibaba.fastjson.JSON;

import com.alibaba.druid.support.json.JSONUtils;
import com.zjitc.backend_shop.mapper.AdminMapper;
import com.zjitc.backend_shop.pojo.Admin;
import com.zjitc.backend_shop.pojo.po.LoginUser;
import com.zjitc.backend_shop.service.AdminService;
import com.zjitc.backend_shop.utils.JwtUtils;
import com.zjitc.backend_shop.utils.MD5WithSaltUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Objects;

@Service
@Transactional
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private AdminMapper adminMapper;

    @Override
    public Admin findAdmin(String username, String password) {
        Example example = new Example(Admin.class);
        example.createCriteria().andEqualTo("username", username).andEqualTo("password", password);
        List<Admin> admin = adminMapper.selectByExample(example);
        if (admin.isEmpty()) {
            return null;
        }
        return admin.get(0);
    }

    @Override
    public Admin findByUsername(String username) {
        Example example = new Example(Admin.class);
        example.createCriteria().andEqualTo("username", username);
        List<Admin> admin = adminMapper.selectByExample(example);
        if (admin.isEmpty()) {
            return null;
        }
        return admin.get(0);
    }

    @Override
    public String login(Admin admin) {
        //封装Authentication对象
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(admin.getUsername(), admin.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("登录失败");
        }
        LoginUser loginUser=(LoginUser)authenticate.getPrincipal();
        String loginUserJson = JSON.toJSONString(loginUser);
        String jwt = JwtUtils.generateToken(loginUserJson);
        return jwt;
    }

    @Override
    public boolean changePassword(Admin admin) {
        MD5WithSaltUtil md5WithSaltUtil = new MD5WithSaltUtil();
        String encryptWithFixedSalt = md5WithSaltUtil.encryptWithFixedSalt(admin.getPassword());

        // 创建Example对象来指定查询条件
        Example example = new Example(Admin.class);
        example.createCriteria().andEqualTo("username", admin.getUsername());

        // 创建一个新的Admin对象，只包含需要更新的字段（密码）
        Admin updatedAdmin = new Admin();
        updatedAdmin.setPassword(encryptWithFixedSalt);

        // 使用updateByExampleSelective方法来更新数据库中的记录
        int affectedRows = adminMapper.updateByExampleSelective(updatedAdmin, example);

        // 如果受影响的行数大于0，说明更新成功
        return affectedRows > 0;
    }

    @Override
    public boolean changeAvator(Admin admin) {
        // 创建Example对象来指定查询条件
        Example example = new Example(Admin.class);
        example.createCriteria().andEqualTo("username", admin.getUsername());

        // 创建一个新的Admin对象，只包含需要更新的字段（头像）
        Admin updatedAdmin = new Admin();
        updatedAdmin.setAvatar(admin.getAvatar());

        // 使用updateByExampleSelective方法来更新数据库中的记录
        int affectedRows = adminMapper.updateByExampleSelective(updatedAdmin, example);

        // 如果受影响的行数大于0，说明更新成功
        return affectedRows > 0;
    }

    @Override
    public List<Admin> findAllAdmin() {
        return adminMapper.selectAll();
    }


}
